#!/usr/bin/php
<?php

$script_directory = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], '/'));
set_include_path(get_include_path().":$script_directory");
require("perfsonarnc.cfg.php");

$in=fopen("php://stdin","r");
$start=microtime();

//Connect to server
if (($socket=fsockopen("unix://".$cfg['socket'])) === false)
	die("fsockopen() failed\n");

//Send hello message
while(true) {
	if(($str=fgets($socket)) == false)
		die("Error reading hello message\n");
	print $str;
	if(rtrim($str)=="]]>]]>")
		break;
}

$hello=false;
$str="";
while(($ch=fgetc($in))!==FALSE) {
	if($ch!="\n")
		$str.=$ch;
	if(substr($str,-6,6)=="]]>]]>")
		if(preg_match("/(.*)\]\]>\]\]>/",$str,$m)) {
			if(fwrite($socket,$m[1]."\n"."]]>]]>\n") == false)
				die("Error sending msg to server\n");
			while($hello) {
				if(($str=fgets($socket)) == false)
					die("Error reading message from server\n");
				print $str;
				if(rtrim($str)=="]]>]]>")
					break;
			}	
			$hello=true;
		$str="";
		} 
}

if(fwrite($socket,"<rpc message-id='local'
          xmlns='urn:ietf:params:xml:ns:netconf:base:1.0'>
       <close-session/>
     </rpc>\n]]>]]>\n") == false)
                                die("Error sending msg to server\n");
while(true) {
	if(($str=fgets($socket)) == false)
		die("Error reading message from server\n");
	if(rtrim($str)=="]]>]]>")
		break;
}

fclose($socket);
?>
